package com.kly.smartbi.controller.bi;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.kly.smartbi.annotation.AuthCheck;
import com.kly.smartbi.common.BaseResponse;
import com.kly.smartbi.common.DeleteRequest;
import com.kly.smartbi.common.ErrorCode;
import com.kly.smartbi.common.ResultUtils;
import com.kly.smartbi.constant.UserConstant;
import com.kly.smartbi.exception.BusinessException;
import com.kly.smartbi.exception.ThrowUtils;
import com.kly.smartbi.model.dto.chart.ChartAddRequest;
import com.kly.smartbi.model.dto.chart.ChartEditRequest;
import com.kly.smartbi.model.dto.chart.ChartQueryRequest;
import com.kly.smartbi.model.dto.chart.ChartUpdateRequest;
import com.kly.smartbi.model.entity.Chart;
import com.kly.smartbi.model.entity.User;
import com.kly.smartbi.model.vo.ChartVO;
import com.kly.smartbi.service.ChartService;
import com.kly.smartbi.service.UserService;
import com.kly.smartbi.utils.BloomFilterUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.kly.smartbi.constant.ChartRedisConstant.*;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private BloomFilterUtil bloomFilterUtil;

    private RBloomFilter<String> bloomFilter;

    @PostConstruct
    public void init() {
        // 在Spring Bean初始化完成后创建布隆过滤器
        this.bloomFilter = bloomFilterUtil
                .create(CHART_GET_BLOOM_NAME, 1000000, 0.001);
    }

    /**
     * caffeine 多级缓存 防止缓存雪崩
     */
    public final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(10_000)
            .build();

    // region 增删改查
    @PostMapping("/add/id")
    public BaseResponse<String> addChartId() {
        List<Chart> list = chartService.list();
        for (Chart chart : list) {
            bloomFilter.add(chart.getId().toString());
        }
        return ResultUtils.success("ok");
    }

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);

        chartService.validChart(chart, true);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        // 添加到布隆过滤器
        bloomFilter.add(String.valueOf(newChartId));
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        // 删除缓存
        String key = String.format("%s%s", CHART_GET_KEY, id);
        stringRedisTemplate.delete(key);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        // 参数校验
        chartService.validChart(chart, false);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 删除缓存
        String key = String.format("%s%s", CHART_GET_KEY, id);
        stringRedisTemplate.delete(key);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ChartVO> getChartVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查询缓存
        String key = String.format("%s%s", CHART_GET_KEY, id);
        String chartCache = LOCAL_CACHE.getIfPresent(key);
        if (StrUtil.isNotBlank(chartCache)) {
            return ResultUtils.success(JSONUtil.toBean(chartCache, ChartVO.class));
        }

        chartCache = stringRedisTemplate.opsForValue().get(key);
        // 判断缓存
        if (StrUtil.isNotBlank(chartCache)) {
            LOCAL_CACHE.put(key, chartCache);
            return ResultUtils.success(JSONUtil.toBean(chartCache, ChartVO.class));
        }
        if ("".equals(chartCache)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图表不存在");
        }
        // bloom 过滤器
        if (!bloomFilter.contains(String.valueOf(id))) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表不存在");
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            // 缓存空值
            stringRedisTemplate.opsForValue().set(key, "", TEN_TIME_TTL, TimeUnit.MINUTES);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        ChartVO chartVO = chartService.getChartVO(chart, request);
        // 写入缓存 过期时间随机 防止缓存雪崩
        int expireTime = TEN_TIME_TTL + RandomUtil.randomInt(1, 5);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(chartVO), expireTime, TimeUnit.MINUTES);
        // 加入local
        LOCAL_CACHE.put(key, JSONUtil.toJsonStr(chartVO));
        bloomFilter.add(String.valueOf(id));
        return ResultUtils.success(chartVO);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ChartVO>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                         HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartService.getChartVOPage(chartPage, request));
    }

    /**
     * 分页获取当前图表创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ChartVO>> listMyChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                           HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartService.getChartVOPage(chartPage, request));
    }

    // endregion


    /**
     * 编辑（图表）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        // 参数校验
        chartService.validChart(chart, false);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 删除缓存
        String key = String.format("%s%s", CHART_GET_KEY, id);
        stringRedisTemplate.delete(key);
        return ResultUtils.success(true);
    }


    /**
     * 根据AI生成图表数据
     */
    @PostMapping("/gen")
    public BaseResponse<ChartVO> genChartByAi(@RequestPart("file") MultipartFile file, ChartAddRequest chartAddRequest) {
        ThrowUtils.throwIf(chartAddRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(chartService.genChartByAi(chartAddRequest, file));
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFileByTest(@RequestPart("file") MultipartFile multipartFile) {
        log.info("uploadFile {}", multipartFile.getOriginalFilename());
        return ResultUtils.success("ok");
    }


    /**
     * 根据AI生成图表数据 并且使用消息队列
     */
    @PostMapping("/gen/byMq")
    public BaseResponse<ChartVO> genChartByAiWithMq(@RequestPart("file") MultipartFile file, ChartAddRequest chartAddRequest) {
        ThrowUtils.throwIf(chartAddRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(chartService.genChartByAiWithMq(chartAddRequest, file));
    }
}
